<?php

namespace app\api\controller\kuyou\order;

use app\common\controller\Api;
use app\common\library\Ems;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use app\api\library\kuyou\Auth;
class User extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth_s;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth_s = new Auth();
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $this->auth_s->init($token);
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth_s->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('请输入账户和密码'));
        }
        $ret = $this->auth_s->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('登陆成功'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth_s->direct($user->id);
        } else {
            $ret = $this->auth_s->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        //$username = $this->request->post('username');
        $username = $this->request->post('mobile');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth_s->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth_s->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth_s->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('参数错误'));
        }
        $this->auth_s->logout();
        $this->success(__('退出成功'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $data = [];
        if(!empty($nickname)){
            $data['nickname'] = $nickname;
        }
        if(!empty($avatar)){
            $data['avatar'] = $avatar;
        }
        $user = $this->auth_s->getUser();
        if(empty($user)){
            $this->error('请先登录');
        }
        $user = Db::name('kuyou_user')->where(['id'=>$user['id']])->find();
        if(empty($user)){
            $this->error('请先登录');
        }
        $res = Db::name('kuyou_user')->where(['id'=>$user['id']])->update($data);
        if($res){
            $this->success('更新成功');
        }
        $this->error('更新失败');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $auth = new Auth();
        $user = $auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth_s->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error('参数错误','',500);
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式错误','',500);
        }
        if (\app\api\model\kuyou\kuyouUser::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error('手机号已绑定','',500);
        }
        $result = (new \app\api\controller\kuyou\order\Sms())->check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error('验证码错误','',500);
        }

        $customer = Db::name('kuyou_customers')->where(['customer_mobile'=>$mobile])->find();
        if(empty($customer)){
            $this->error('此手机号尚未成为客户，不可绑定','',500);
        }
        Db::name('kuyou_user')->where(['id'=>$user['id']])->update([
            'binding'=>'1',
            'customers_id'=>$customer['id'],
            'username'=>$mobile,
            'mobile'=>$mobile
        ]);

        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->username = $mobile;
        $user->mobile = $mobile;
        $user->save();

        (new \app\api\controller\kuyou\order\Sms())->flush($mobile, 'changemobile');
        $this->success(__('绑定成功'), '',200);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error('参数错误','',500);
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error('手机号格式错误','',500);
            }
            $user = \app\api\model\kuyou\kuyouUser::getByMobile($mobile);
            if (!$user) {
                $this->error('未找到用户或用户未绑定手机号','',500);
            }
            $ret = (new \app\api\controller\kuyou\order\Sms())->check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error('验证码错误','',500);
            }
            (new \app\api\controller\kuyou\order\Sms())->flush($mobile, 'resetpwd');
        } else {
            $this->error('类型错误','',500);
        }
        //模拟一次登录
        $this->auth_s->direct($user->id);
        $ret = $this->auth_s->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('密码修改成功'),'',200);
        } else {
            $this->error($this->auth_s->getError(),'',500);
        }
    }

    /**
     * 通过token获取用户信息
     * @ApiMethod (POST)
     */
    public function userInfo($json = false)
    {
        $data = $this->auth_s->getUserinfo();
        $data['avatar'] = $data['avatar'] ? cdnurl($data['avatar'], true) : '';
        if ($json == true) {
            return $data;
        }
        $this->success('用户信息', ['userinfo'=>$data],'200');
    }

}
